package sistemioperativi.monitor.es9;

import java.util.concurrent.TimeUnit;
import java.util.*;
public class TestMonitorAndrea implements Runnable{
	
	private static final int min = 1;
	private static final int max = 3;
	Random random = new Random();
	Hoare2 m = new Hoare2();
	
	
    public void run() {
        while (true) {
                try {
                        m.lock();
                        System.out.println("Inizio operazioni thread " + Thread.currentThread().getId());
                        attesaCasuale();
                        while (condizioneCasuale()) m.await();
                        attesaCasuale();
                        if (condizioneCasuale() || condizioneCasuale()) m.signal();
                        //else m.signalAll();
                        attesaCasuale();
                        System.out.println("Fine operazioni thread " + Thread.currentThread().getId());
                } catch(Exception e) {
                } finally {
                        m.unlock();
                }
        }	
    }// run
    
    private void attesaCasuale() throws Exception{
    	attendi(min,max);
    }
    
    private void attendi(int min, int max) throws InterruptedException{
    	TimeUnit.SECONDS.sleep(random.nextInt(max-min+1)+min);
    }
    
    private boolean condizioneCasuale(){
    	
    	int x = random.nextInt();
    	if(x%2 == 0)
    		return true;
    	return false;
    }
    
    
}//EOC
